#include "supplierdialog.h"
#include <QLineEdit>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QString>
#include <QValidator>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QPalette>
#include <cstring> // For strncpy

extern "C" {
#include "../backend/supplier.h"
}

SupplierDialog::SupplierDialog(QWidget* parent, const Supplier* init, bool idEditable)
    : QDialog(parent)
{
    setWindowTitle(init ? "编辑供应商" : "添加供应商");
    QFormLayout* form = new QFormLayout(this);

    idEdit = new QLineEdit;
    nameEdit = new QLineEdit;
    contactEdit = new QLineEdit;
    phoneEdit = new QLineEdit;
    addressEdit = new QLineEdit;

    // 设置验证器
    setupValidators();

    // 根据验证规则设置最大长度
    nameEdit->setMaxLength(50);
    contactEdit->setMaxLength(30);
    phoneEdit->setMaxLength(20);
    addressEdit->setMaxLength(100);

    form->addRow("ID (1-6位数字):", idEdit);
    form->addRow("名称 (英文数字，1-50字符):", nameEdit);
    form->addRow("联系人 (英文数字，1-30字符):", contactEdit);
    form->addRow("电话 (数字-空格()，最多20字符):", phoneEdit);
    form->addRow("地址 (可选，最多100字符):", addressEdit);

    if (init) {
        idEdit->setText(QString::number(init->id));
        nameEdit->setText(init->name);
        contactEdit->setText(init->contact_person);
        phoneEdit->setText(init->phone);
        addressEdit->setText(init->address);
        if (!idEditable) {
            idEdit->setReadOnly(true);
        }
    }

    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    form->addWidget(buttonBox);

    connect(buttonBox, &QDialogButtonBox::accepted, this, &SupplierDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &SupplierDialog::reject);
    
    // 连接实时验证信号
    connect(idEdit, &QLineEdit::textChanged, this, &SupplierDialog::validateInput);
    connect(nameEdit, &QLineEdit::textChanged, this, &SupplierDialog::validateInput);
    connect(contactEdit, &QLineEdit::textChanged, this, &SupplierDialog::validateInput);
    connect(phoneEdit, &QLineEdit::textChanged, this, &SupplierDialog::validateInput);
    connect(addressEdit, &QLineEdit::textChanged, this, &SupplierDialog::validateInput);
}

void SupplierDialog::setupValidators() {
    // ID验证器：1-6位数字
    QRegularExpressionValidator* idValidator = new QRegularExpressionValidator(
        QRegularExpression("^[1-9]\\d{0,5}$"), this);
    idEdit->setValidator(idValidator);
    
    // 名称验证器：中英文数字，允许空格
    QRegularExpression supNameRegex(QStringLiteral("^[a-zA-Z0-9]{1,50}$"));
    qDebug() << "SupplierDialog Name - Pattern:" << supNameRegex.pattern()
             << "Valid:" << supNameRegex.isValid()
             << "Error:" << supNameRegex.errorString();
    QValidator *supNameValidator = new QRegularExpressionValidator(supNameRegex, this);
    nameEdit->setValidator(supNameValidator);
    
    // 联系人验证器：中英文数字，允许空格
    QRegularExpression supContactRegex(QStringLiteral("^[a-zA-Z0-9]{1,30}$"));
    qDebug() << "SupplierDialog Contact - Pattern:" << supContactRegex.pattern()
             << "Valid:" << supContactRegex.isValid()
             << "Error:" << supContactRegex.errorString();
    QValidator *supContactValidator = new QRegularExpressionValidator(supContactRegex, this);
    contactEdit->setValidator(supContactValidator);
    
    // 电话验证器：数字、连字符、空格、括号、加号
    QRegularExpressionValidator* phoneValidator = new QRegularExpressionValidator(
        QRegularExpression("^[0-9\\-\\s\\(\\)\\+]{0,20}$"), this);
    phoneEdit->setValidator(phoneValidator);
}

void SupplierDialog::validateInput() {
    QLineEdit* sender = qobject_cast<QLineEdit*>(QObject::sender());
    if (!sender) return;
    
    QPalette palette;
    bool isValid = true;
    QString tooltip;
    
    if (sender == idEdit) {
        int id = idEdit->text().toInt();
        isValid = validate_supplier_id_field(id);
        tooltip = isValid ? "" : "供应商ID必须是1-6位的正整数";
    } else if (sender == nameEdit) {
        QByteArray nameBytes = nameEdit->text().toUtf8();
        isValid = validate_supplier_name(nameBytes.constData());
        tooltip = isValid ? "" : "供应商名称必须是1-50个字符，支持英文和数字，不能有特殊符号（空格除外）";
    } else if (sender == contactEdit) {
        QByteArray contactBytes = contactEdit->text().toUtf8();
        isValid = validate_supplier_contact(contactBytes.constData());
        tooltip = isValid ? "" : "联系人必须是1-30个字符，支持英文和数字，不能有特殊符号（空格除外）";
    } else if (sender == phoneEdit) {
        QByteArray phoneBytes = phoneEdit->text().toUtf8();
        isValid = validate_supplier_phone(phoneBytes.constData());
        tooltip = isValid ? "" : "电话号码最多20个字符，只能包含数字、连字符、空格、括号和加号";
    } else if (sender == addressEdit) {
        QByteArray addressBytes = addressEdit->text().toUtf8();
        isValid = validate_supplier_address(addressBytes.constData());
        tooltip = isValid ? "" : "地址不能超过100个字符，且不能包含恶意脚本标签";
    }
    
    if (!isValid) {
        palette.setColor(QPalette::Base, QColor(255, 200, 200)); // 淡红色背景
    }
    
    sender->setPalette(palette);
    sender->setToolTip(tooltip);
}

void SupplierDialog::accept() {
    // 在填充之前清除结构体
    memset(&data, 0, sizeof(Supplier));

    // 获取并验证数据
    bool ok_id;
    data.id = idEdit->text().toInt(&ok_id);

    // 复制字符串数据
    strncpy(data.name, nameEdit->text().toUtf8().constData(), SUPPLIER_NAME_LEN - 1);
    data.name[SUPPLIER_NAME_LEN - 1] = '\0';

    strncpy(data.contact_person, contactEdit->text().toUtf8().constData(), SUPPLIER_CONTACT_LEN - 1);
    data.contact_person[SUPPLIER_CONTACT_LEN - 1] = '\0';

    strncpy(data.phone, phoneEdit->text().toUtf8().constData(), SUPPLIER_PHONE_LEN - 1);
    data.phone[SUPPLIER_PHONE_LEN - 1] = '\0';

    strncpy(data.address, addressEdit->text().toUtf8().constData(), SUPPLIER_ADDRESS_LEN - 1);
    data.address[SUPPLIER_ADDRESS_LEN - 1] = '\0';

    // 使用后端验证函数进行完整验证
    char error_msg[512];
    if (!validate_supplier_data(&data, error_msg, sizeof(error_msg))) {
        QMessageBox::warning(this, "数据验证失败", QString("验证错误：%1").arg(error_msg));
        return;
    }

    // 如果所有验证都通过，则接受对话框
    QDialog::accept();
}